package main

//自定义中间件

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

var limitChan = make(chan struct{}, 5000)
var RuntimeCount int

func timeMiddleWare(next http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		//begin := time.Now()
		next.ServeHTTP(rw, r)
		//timeElapsed := time.Since(begin)
		//log.Printf("%s request %s use %d ms\n", r.RemoteAddr, r.RequestURI, timeElapsed.Milliseconds())
	})
}

// LimitMiddleWare 自定义限流qps
func LimitMiddleWare(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		limitChan <- struct{}{}                       //协程池 limitChan 用满时阻塞
		log.Printf("cocurrence %d\n", len(limitChan)) //当前qps的协程数
		inner.ServeHTTP(rw, r)
		<-limitChan
	})
}

func IndexHandle(rw http.ResponseWriter, r *http.Request) {
	time.Sleep(150 * time.Millisecond)
	fmt.Fprintf(rw, "in index")
}

func main() {
	http.Handle("/", LimitMiddleWare(timeMiddleWare(http.HandlerFunc(IndexHandle))))
	http.ListenAndServe(":8080", nil)
}
